from flask import Flask, request, jsonify, Response
from flask_cors import CORS
import json
from main import DialysisAIAssistant

app = Flask(__name__)
CORS(app, origins=["http://localhost:8080"])

assistant = DialysisAIAssistant(api_key="b6.a3va7MgbHK9dglYQ")

@app.route('/analyze', methods=['POST'])
def analyze():
    data = request.json
    result = assistant.analyze_data(data)
    return jsonify({"response": result})

@app.route('/chat', methods=['POST', 'GET'])
def chat():
    if request.method == 'GET':
        query = request.args.get('query')
        context = request.args.get('context')
    else:
        data = request.json
        query = data.get('query')
        context = data.get('context')
    
    def generate():
        response = assistant.chat_stream(query, context)
        for chunk in response:
            yield f"data: {json.dumps({'content': chunk})}\n\n"
    
    return Response(generate(), mimetype='text/event-stream')

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
